package com.wu.leetcode.leetcode39;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Leetcode39-组合总和
 *
 * @author lynn
 * @date 2020/8/13 - 16:40
 */
public class Solution {
    static List<List<Integer>> res = new ArrayList<>();

    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        if (candidates == null || candidates.length == 0) {
            return res;
        }
        Arrays.sort(candidates);
        dfs(candidates, target, 0, new ArrayList<Integer>());
        return res;
    }

    private static void dfs(int[] candidates, int target, int i, ArrayList<Integer> list) {
        if (target < 0) {
            return;
        } else if (target == 0) {
            res.add(new ArrayList<>(list));
        } else {
            for (int j = i; j < candidates.length && target >= candidates[j]; j++) {
                list.add(candidates[j]);
                dfs(candidates, target - candidates[j], j, list);
                list.remove(list.size() - 1);
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = new int[]{2, 3, 5};
        List<List<Integer>> lists = combinationSum(arr, 8);
        System.out.println(lists);
    }
}
